package com.avecsys.quotemanager.service.user;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.avecsys.quotemanager.dao.common.EnumDBRecordStatus;
import com.avecsys.quotemanager.dao.common.EnumTransactionStatus;
import com.avecsys.quotemanager.dao.user.UserMasterDAO;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.exception.DAOException;
import com.avecsys.quotemanager.pojos.SupplierMasterPojo;
import com.avecsys.quotemanager.pojos.UserMasterPojo;

public class UserMasterServiceImpl implements UserMasterService {

	private static final Log log = LogFactory
			.getLog(UserMasterServiceImpl.class);

	private UserMasterDAO userMasterDAO;

	/**
	 * @return the userMasterDAO
	 */
	public UserMasterDAO getUserMasterDAO() {
		return userMasterDAO;
	}

	/**
	 * @param userMasterDAO
	 *            the userMasterDAO to set
	 */
	public void setUserMasterDAO(UserMasterDAO userMasterDAO) {
		this.userMasterDAO = userMasterDAO;
	}

	@Override
	public Integer saveSupplierUser(UserMasterPojo userMasterPojo)
			throws BusinessException {
		Integer transactionStatus = EnumTransactionStatus.FAIL.ordinal();
		try {
			// Step1:
			// if the Supplier Master information already persisted then update
			// other wise create a new supplier information with default use
			// Mark As Active
			userMasterPojo.setStatus(EnumDBRecordStatus.ACTIVE.status());
			if (userMasterPojo.isPersisted()) {
				// Check default Administrator is avaiable
				transactionStatus = userMasterDAO.update(userMasterPojo);
			} else {
				// Create New Supplier With Default Administrator
				transactionStatus = userMasterDAO.save(userMasterPojo);
			}
		} catch (DAOException e) {
			log.error(e);
			throw new BusinessException(e);
		}
		return transactionStatus;
	}

	/**
	 * Method to return the userMasterPojo instance by id
	 * 
	 * @param userId
	 * @return UserMasterPojo
	 * @throws BusinessException
	 */
	@Override
	public UserMasterPojo getUserMasterById(Long userId)
			throws BusinessException {
		UserMasterPojo userMasterPojo = new UserMasterPojo();
		try {
			userMasterPojo = userMasterDAO.findById(userMasterPojo, userId);
		} catch (DAOException e) {
			throw new BusinessException(e);
		}
		return userMasterPojo;
	}

	@Override
	public Integer deleteSupplierUser(SupplierMasterPojo supplierMasterPojo,
			Long userId) throws BusinessException {
		Integer transactionStatus = EnumTransactionStatus.FAIL.ordinal();
		UserMasterPojo userMasterPojo = getUserMasterById(userId);
		try {
			transactionStatus = userMasterDAO.delete(userMasterPojo);
		} catch (DAOException e) {
			throw new BusinessException(e);
		}
		return transactionStatus;
	}
}
